/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package be.ugent.medirem.persistence.facade;

import be.ugent.medirem.persistence.entity.Unit;
import be.ugent.medirem.persistence.entity.details.UnitDetails;
import be.ugent.medirem.persistence.exception.UnitNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Thomas Roelens <thomas.roelens@ugent.be>
 */
@Stateless
public class UnitDaoBean implements UnitDaoLocal {

    @PersistenceContext
    private EntityManager em;

    public Long create(String name) throws IllegalArgumentException {
        Unit unit = null;

        if (name == null) {
            throw new IllegalArgumentException("Unit name is null");
        }

        try {
            unit = new Unit(name);
            em.persist(unit);
        } catch (Exception ex) {
            throw new EJBException(ex);
        }

        return unit.getId();
    }

    public void remove(Long id) throws IllegalArgumentException, UnitNotFoundException {
        Unit unit = null;
        if (id == null) {
            throw new IllegalArgumentException("Unit id is null");
        }
        try {
            unit = em.find(Unit.class, id);

            if (unit == null) {
                throw new UnitNotFoundException();
            } else {
                unit = em.merge(unit);
                em.remove(unit);
            }
        } catch (Exception ex) {
            throw new EJBException(ex);
        }
    }

    public UnitDetails getUnit(Long id) throws IllegalArgumentException {
        Unit unit = null;
        if (id == null) {
            throw new IllegalArgumentException("Unit id is null");
        }
        try {
            unit = em.find(Unit.class, id);

            if (unit == null) {
                throw new UnitNotFoundException();
            }
        } catch (Exception ex) {
            throw new EJBException(ex);
        }
        return new UnitDetails(unit.getId(), unit.getName());
    }

    public Long getUnitId(String name) throws IllegalArgumentException, UnitNotFoundException {
        Unit unit = null;
        try {
            unit = (Unit) em.createNamedQuery("Unit.FindByName").setParameter("name", name).getResultList().get(0);
            if (unit == null) {
                throw new UnitNotFoundException();
            }
        } catch (Exception ex) {
            throw new IllegalArgumentException("Unit name invalid");
        }
        return unit.getId();
    }

    public List<UnitDetails> getAll() {
        List<UnitDetails> list = new ArrayList<UnitDetails>();

        List<Unit> unitList = em.createNamedQuery("Unit.FindAll").getResultList();
        for(Unit u : unitList) {
            list.add(new UnitDetails(u.getId(), u.getName()));
        }

        return list;
    }
}
